""" -*- coding: utf-8 -*-"""
from flask import Blueprint, request, jsonify, g, current_app
from models import db, Project, Department, User, ProjectType, ProjectProgress, File
from extends.auth import require_role


project_bp = Blueprint('project', __name__, url_prefix='/projects')


@project_bp.route('/', methods=['POST'])
@require_role('project_coordinator')
def create_project():
    """创建新项目"""
    data = request.get_json()
    required_fields = ['name', 'department_id', 'coordinator_id', 'selected_code']
    for field in required_fields:
        if field not in data:
            return jsonify({'error': f'Missing required field: {field}'}), 400

    # 验证部门是否存在
    department = Department.query.get(data['department_id'])
    if not department:
        return jsonify({'error': 'Department not found'}), 404

    # 验证协调人是否存在
    coordinator = User.query.get(data['coordinator_id'])
    if not coordinator:
        return jsonify({'error': 'Coordinator not found'}), 404

    # 验证选择的部门编号是否属于该部门
    selected_code_valid = any(code.value == data['selected_code'] for code in department.codes)
    if not selected_code_valid:
        return jsonify({'error': 'Selected code does not belong to this department'}), 400

    # 生成项目编号
    project_number = Project.generate_project_number(data['department_id'], data['selected_code'])
    if not project_number:
        return jsonify({'error': 'Failed to generate project number'}), 500

    # 创建项目
    new_project = Project(
        name=data['name'],
        project_number=project_number,
        department_id=data['department_id'],
        creator_id=g.current_user.id,
        coordinator_id=data['coordinator_id'],
        project_type_id=data.get('project_type_id')
    )

    try:
        db.session.add(new_project)
        db.session.commit()
        return jsonify({
            'message': 'Project created successfully',
            'project': new_project.to_dict_full()
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'Database error: {str(e)}'}), 500


@project_bp.route('/', methods=['GET'])
def get_projects():
    """获取所有项目"""
    projects = Project.query.all()
    return jsonify({
        'count': len(projects),
        'projects': [p.to_dict_full() for p in projects]
    })


@project_bp.route('/<int:project_id>', methods=['GET'])
def get_project(project_id):
    """获取单个项目详情"""
    project = Project.query.get(project_id)
    if not project:
        return jsonify({'error': 'Project not found'}), 404

    # 获取项目进度
    progresses = ProjectProgress.query.filter_by(project_id=project_id).all()
    # 获取项目文件
    files = File.query.filter_by(project_id=project_id).all()

    project_data = project.to_dict_full()
    project_data['progresses'] = [p.to_dict() for p in progresses]
    project_data['files'] = [f.to_dict() for f in files]

    return jsonify(project_data)


@project_bp.route('/<int:project_id>/progress', methods=['POST'])
@require_role('designer')
def add_project_progress(project_id):
    """添加项目进度（设计师）"""
    data = request.get_json()
    if not data or 'description' not in data:
        return jsonify({'error': 'Missing progress description'}), 400

    # 验证项目是否存在
    project = Project.query.get(project_id)
    if not project:
        return jsonify({'error': 'Project not found'}), 404

    new_progress = ProjectProgress(
        project_id=project_id,
        user_id=g.current_user.id,
        description=data['description']
    )

    try:
        db.session.add(new_progress)
        db.session.commit()
        return jsonify({
            'message': 'Project progress added successfully',
            'progress': new_progress.to_dict()
        }), 201
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'Database error: {str(e)}'}), 500